﻿using AvaVSExt.Helpers;
using System.Collections.Generic;

namespace AvaVSExt.Xaml
{
    public class UsingPair
    {
        public string ShortName { get; set; }
        public string NamespaceName { get; set; }

        public override string ToString()
        {
            return $"xmlns:{ShortName}=\"using:{NamespaceName}\"";
        }
    }

    public class XamlInfo
    {
        public List<UsingPair> Namespaces { get; set; } = new List<UsingPair>();
        public string DataType { get; set; }
        public string ClassName { get; set; }

        public string GetNamespaceFromClassName()
        {
            var lastDot = ClassName.LastIndexOf('.');
            return ClassName.Substring(0, lastDot);
        }
        
        public static XamlInfo Parse(string text)
        {
            var usings = GetUsings(text);

            var dataType = XmlHelper.GetAttributeBeforeSpecialToken(text, "x:DataType", ">");
            var className = XmlHelper.GetAttributeBeforeSpecialToken(text, "x:Class", ">");

            return new XamlInfo()
            {
                DataType = dataType,
                Namespaces = usings,
                ClassName = className,
            };
        }

        private static List<UsingPair> GetUsings(string text)
        {
            var startIndex = 0;
            var namespaceNameList = new List<UsingPair>();
            while (startIndex >= 0)
            {
                var usingPair = GetUsing(text, startIndex, out var nextStartIndex);
                startIndex = nextStartIndex;
                if (usingPair is null) break;
                namespaceNameList.Add(usingPair);
            }
            return namespaceNameList;
        }

        private static UsingPair GetUsing(string text, int startIndex, out int nextStartIndex)
        {
            nextStartIndex = -1;
            const string UsingToken = "=\"using:";
            const string CloseToken = "\"";
            const string XmlnsToken = "xmlns:";
            var openIndex = text.IndexOf(UsingToken, startIndex);

            if (openIndex < 0) return null;

            var closeIndex = text.IndexOf(CloseToken, openIndex + UsingToken.Length);

            if (closeIndex < 0) return null;

            var xmlnsIndex = text.LastIndexOf(XmlnsToken, openIndex);

            if (xmlnsIndex < 0) return null;

            var shortName = text.Substring(xmlnsIndex + XmlnsToken.Length, openIndex - xmlnsIndex - XmlnsToken.Length);
            var namespaceName = text.Substring(openIndex + UsingToken.Length, closeIndex - openIndex - UsingToken.Length);

            nextStartIndex = closeIndex + 1;

            return new UsingPair() { NamespaceName = namespaceName, ShortName = shortName };
        }

    }
}
